const server = require('express')();
const url = require('url');
const fs = require('fs');
const mysql = require('mysql');
const expressStatic = require('express-static');
const port = 81;
// 后端独立处理跨域问题
// server.all('*', function(req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
//     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//     next();
// });
let sql = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '123456',
  database : 'fl'
});
sql.connect();
//  列表页
server.get(`/getAllgoods`,(request,response)=>{
	// let id = url.parse(req.url,true).query.id;
	sql.query(`SELECT * FROM feile`,(error,data)=>{
		if(error){
			console.log(error)
			response.end("error")
		}
		else{
			response.end(JSON.stringify(data))
		}
	})
})
// 详情页
server.get(`/getDetails`,(request,response)=>{
	let id = url.parse(request.url,true).query.id;

	if(id === undefined){
		response.end("缺少id");
		return;
	}

	sql.query(`SELECT * FROM feile WHERE id=${id}`,(error,data)=>{
		if(error){
			console.log(error)
			response.end("error")
		}
		else{
			if(data.length === 0){
				response.end("查无此物");
				return;
			}
			response.end(JSON.stringify(data))
		}
	})
})
server.get("/addData",(rep,res)=>{
    // 注册
    // let id = url.parse(rep.url,true).query.id;
    let tel= url.parse(rep.url,true).query.tel;
    let paw = url.parse(rep.url,true).query.paw;
    sql.query(`INSERT INTO user (tel,paw) VALUES ("${tel}","${paw}")`,function(error,data){
        if(error){         
          console.log(error)
           console.log("传输失败")
        }else{
            res.end(JSON.stringify(data))
            console.log("shujuchuanshu is ok")
        }

    })
})
server.get("/addCity",(rep,res)=>{
    // 注册
    // let id = url.parse(rep.url,true).query.id;
    let names= url.parse(rep.url,true).query.names;
	let phones = url.parse(rep.url,true).query.phones;
	let city = url.parse(rep,url,true).query.city
	console.log(city)
	console.log(names)
	console.log(phones)
    sql.query(`INSERT INTO user (names,phones,city) VALUES ("${names}","${phones}","${city}")`,function(error,data){
        if(error){         
          console.log(error)
           console.log("传输失败")
        }else{
            res.end(JSON.stringify(data))
            console.log("shujuchuanshu is ok")
        }

    })
})
server.get("/userData",(req,res)=>{
	// 登陆 注册
	let tel= url.parse(req.url,true).query.tel;
	
    sql.query(`SELECT * FROM user WHERE tel="${tel}"`,function(error,data){
        if(error){
           res.end(error)
           console.log("传输失败")
        }else{
            res.end(JSON.stringify(data))
            console.log("shujuchuanshu is ok")
        }

    })
})
server.use(expressStatic(__dirname + '/static'))
server.listen(port);
console.log(`server is running at ${port}`)